package com.fosafer.idcard_demo.util;

import android.app.Activity;

import java.util.Stack;

/**
 * Create By :   IDEA
 * Package:      [com.fosafer.idcard_demo.util]
 * ClassName:    [AppManagerUtil]
 * Description:  [AppMangerUtil工具类]
 * Author:       [jianzhic]
 * CreateDate:   [16-4-12 15:05]
 * UpdateUser:   [jianzhic]
 * UpdateDate:   [16-5-12 15:05]
 * UpdateRemark: [Update Description]
 * Version:      [v1.0.0]
 * <p>
 * Copyright (c) 2016 Fosafer Co.,Ltd. All rights reserved.
 */
public class AppManagerUtil {


    /**
     * Activity栈
     */
    private static Stack<Activity> activityStack;
    /**
     * 单例模式
     */
    private static volatile AppManagerUtil instance;

    private AppManagerUtil() {
    }

    /**
     * 单一实例
     */
    public static AppManagerUtil getInstance() {
        if (instance == null) {
            instance = new AppManagerUtil();
        }
        return instance;
    }


    /**
     * 是否在栈中
     */
    private Activity isHere(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 是否在栈中
     */
    private Activity isHere(String actName) {
        for (Activity activity : activityStack) {
            if (activity.getClass().getSimpleName().equals(actName)) {
                return activity;
            }
        }
        return null;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addAct(Activity act) {
        if (activityStack == null) {
            activityStack = new Stack<>();
        }
        activityStack.add(act);
    }

    /**
     * 当前Act.
     *
     * @return Activity.
     */
    public Activity currentAct() {
        Activity activity = null;
        if (activityStack != null && !activityStack.isEmpty()) {
            activity = activityStack.lastElement();
        }
        return activity;
    }


    /**
     * 结束指定的Activity
     */
    public void removeAct(Activity act) {
        if (null != isHere(act.getClass())) {
            activityStack.remove(act);
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishAct(String actName) {
        Activity activity = isHere(actName);
        if (null != activity) {
            activity.finish();
        }

    }


    /**
     * 结束所有Activity
     */
    private void finishAllActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            if (null != activityStack.get(i)) {
                activityStack.get(i).finish();
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用.
     */
    public void appExit() {
        finishAllActivity();
    }


}  